/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.servermanager.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.inspur.edp.metadata.rtcustomization.api.exception.ErrorCodes;
import com.inspur.edp.metadata.rtcustomization.api.exception.LcmParseException;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

public class Converterutils {
    /**
     * 单个对象转换为目标类
     *
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> T toTarget(S source, Class<T> tClass) {
        if (Objects.isNull(source)) {
            return null;
        }
        try {
            T target = tClass.newInstance();
            if (Objects.nonNull(target)) {
                BeanUtils.copyProperties(source, target);
            }
            return target;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new LcmParseException(e, ErrorCodes.ECP_PARSE_0010);
        }
    }

    /**
     * List转换为目标类
     *
     * @param source
     * @param tClass
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S extends List, T> List<T> toTargetList(S source, Class<T> tClass) {
        if (CollectionUtils.isEmpty(source)) {
            return new ArrayList<>();
        }
        List<T> targetList = new ArrayList<>(source.size());
        source.forEach(s -> {
            T target = toTarget(s, tClass);
            targetList.add(target);
        });
        return targetList;
    }

}
